<?php
/**
 * Atlas KOTASOFT cakephp
 *
 * Bakes web interface 
 *
 * PHP versions 4 and 5
 *
 * ATLAS KOTASOFT  cakephp web code generator
 * Copyright 2009, Kotasoft agile factory, Inc. (http://www.atlascakephp.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009, Kotasoft agile factory , Inc. (http://www.kotasoft.com)
 * @link          http://www.atlascakephp.com  ATLAS KOTASOFT Project
 * @version       BETA 0.5 $
 * @modifiedby    $LastChangedBy: daniel castanera - guldoe and francisco dominguez - idioto $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

require ("kt_app_controller.php");
/* class KtmodelsController, generate models */
class KtmodelsController extends KtAppController{	
	 
	 
	var $ruta_admin = "/admin/ktmodels/";
	var $modelName = "";
	var $components = array('json');
	
	
	/* index for admin, get tables from database */
	/* TODO  PAGINATOR */
	function admin_index() {
	  $session=$this->Session->read(KT_SESSION); 
 	  $this->set("configuration",$session['Ktconfiguration']);  
 	     
	  if(!$this->__dbConfig()) {
	       $this->Session->setFlash(__('Your configuration is not available',true));	
	       $this->log(__('Your configuration is not available',true), LOG_DEBUG);	 	
	  } 
	  
	  if (!empty($this->data)) {	  	 
			$this->userDbConfig=$this->data['Ktmodel']['selectedbd'];	
					
      }else if (count($session['Ktconfiguration'])>0) {      
	  		$this->userDbConfig = $session['Ktconfiguration']['name']; 
	  }
	  
	  $useDbConfig=$this->userDbConfig;
	  if ($useDbConfig!=""){
					$this->set('configName',$this->userDbConfig);	   
					$this->set('ruta_admin',$this->ruta_admin);	   
					
					$tables=$this->listAll($useDbConfig);
					if(count($tables)> 0)	$this->set('tables', $tables); 		
					else					$this->set('tables', "");					
		    		//$this->__getModelsBd();
	   } else {
				$this->Session->setFlash(__('Your database not have tables available',true));	
				$this->log(__('Your database not have tables available',true), LOG_DEBUG);		
	   }
     	 		
	}
	
	function index(){
		
	}
	
	
	
      
  
    /*  admin generate, let you select configuration from a database you have been choose*/  
	function admin_generate($names=null) {
		
		$this->set("name",$names);		
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	    $this->set("userDbConfig",$this->userDbConfig);	    
 	    $this->set("configuration",$session['Ktconfiguration']);  	   
 	    $this->__model_results($this->userDbConfig,$names); 
 	    $modelName = $this->_modelName($names);	
 	     
 	    
 	    //generate selector with models
 	 	$listTables = $this->__getListTables(); 	 	
 	    if (count($listTables) > 0){
 	    	$this->set('selectTables', $listTables); 	    	
 	    } else {
 	    	$this->set('selectTables', ""); 	    	
 	    }
 	   
 	    	 
 	    
 	    // generate selector for fields of this model
 	    $listModel = $this->__getListFieldsModel($this->userDbConfig,$names); 
	 	if (count($listModel) > 0){
 	    	$this->set('selectModelsField', $listModel); 	    	
 	    } else {
 	    	$this->set('selectModelsField', ""); 	    	
 	    }
 	    
	    if ($names!="") { 
 	    	if (file_exists($this->__getPath() . $modelName . '.php')) {
				$this->Session->setFlash(__('File exists, you are going to overwrite it',true));
				$this->log(__('File exists, you are going to overwrite it',true), LOG_DEBUG);							 			
			}
 	    }
 	     if(!$this->__checkDirectoryProject()){
 	    		$this->Session->setFlash(__('Error directory configuration, files not could be created, check configuration',true));
 	    		$this->log(__('Error directory configuration, files not could be created, check configuration',true), LOG_DEBUG);
 	    		$this->redirect("/admin/ktconfigurations");	
 	    }    
	}
	
	
	/* return path for models */
	function __getPath() {	
	     $session = $this->Session->read(KT_SESSION);	      
		 $path = $session[KT_CONFIGURATION][KT_DIRECTORY]."/app/models".DS; 
		 return $path;
	}
	
	
	
    /* generate render to file */
    function admin_norender($names=null) {
      	
      	// read session configuration
      	$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"];
		 
		// set render layout
		$this->layout ='render_layout';
		
	    // if have datas from form
       $mensaje = $this->__checkDirectory();	    
	    if ($mensaje!=""){
	    	$this->Session->setFlash(__($mensaje,true));	
	    	$this->redirect(array('action' => 'admin_index'));
	    }
	     
		if (!empty($this->data)){
		  $this->modelName=$this->data["Ktmodel"]["names"];	  	  
	  	
	  	  $currentControllerName = $this->_modelName($this->modelName);
		  $pluralModelName =$this->_pluralName($currentControllerName);
		  $singularName = Inflector::variable($currentControllerName);		  
		  $nameClass = Inflector::humanize($pluralModelName);	  	  
	  	  $this->set("currentControllerName",$currentControllerName);
		  $this->set("pluralName",$pluralModelName);			   
		  $this->set("className",$nameClass);
		  
		  $this->set("modelName",$currentControllerName);
		  $this->set("singularName",$singularName);
		  
		  $this->set("pluralModelName",$pluralModelName);		  	  
		  $this->set("singularModelName",$singularName);
		  
		   
		  $useTable = $this->data['Ktmodel']['names'] ;
		  $useDbConfig = $this->data['Ktmodel']['useDbConfig']; 
		  $primaryKey ='id';
		  
		  
		  $this->set("userDbConfig",$this->userDbConfig);
		  
		  
		  // table 
		 /* if (($useTable && $useTable !== Inflector::tableize($names)) 
					|| $useTable === false) {
						$table = "'$useTable'";					
						$this->set("useTable",$table);
		 }
		 */
		$tablename = trim($this->data['Ktmodel']['tablename']);
		if(isset($tablename) && $tablename!=""){
			$this->set("useTable", $this->__getTableName($useTable));
		}
		 // primary key 
		  if ($primaryKey !== 'id') { 
					$this->set("primaryKey",$primaryKey);
		  }
		  
		  
		  
	      // validation 
		  $valid_values = $this->data['Ktmodel']['valid'];
		  if (isset($valid_values)){
			      	 	// llamar a una funcion que devuelva validaciones de campos
			      	 	$out = $this->__getValidate($valid_values);
			      	 	$this->set("validate",$out);
			      	 	
		  }	 
		  
		  $hasOne = $this->data['Ktmodel']['hasOne']; 
		  if (isset($hasOne) && $hasOne[0]["className"]!=""){
			         // llamar a una funcion que devuelva el resultado de codigo de hasOne
			         $out=$this->__getHasOne($hasOne);
			         $this->set("hasOne",$out);
		  }

		  $hasMany = $this->data['Ktmodel']['hasMany']; 
		  if (isset($hasMany) && $hasMany[0]["className"]!=""){
			         // llamar a una funcion que devuelva el resultado de codigo de hasMany
			         $out=$this->__getHasMany($hasMany);
			         $this->set("hasMany",$out);
		  }
		  $belongsTo =$this->data['Ktmodel']['belongsTo'];
		  if (isset($belongsTo) && $belongsTo[0]["className"]!="") {
			      	// llamar a una funcion que devuelva el resultado de codigo de hasMany
			      	$out=$this->__getBelongsTo($belongsTo);
			      	 $this->set("belongsTo",$out);
		  }
	      	 
		  $hasAndBelongsToMany =$this->data['Ktmodel']['hasAndBelongsToMany'];
		  if (isset($hasAndBelongsToMany) && $hasAndBelongsToMany["className"]!="") {
			      	// llamar a una funcion que devuelva el resultado de codigo de hasAndBelongsToMany
			      	$out=$this->__getHasAndBelongsToMany($hasAndBelongsToMany);
			      	$this->set("hasAndBelongsToMany",$out);
		  }		
		  
		  
		 
		  $filename = $this->__getPath() . Inflector::underscore($singularName) . '.php'; 
		  $session=$this->Session->read(KT_SESSION); 			
		  $this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	      
		  
		  
		  // render to file
		  if($this->createFile($filename, $this->render())) {
				$this->Session->setFlash("Modelo creado con exito");
					$this->log(__("Modelo creado con exito",true), LOG_DEBUG);
 	    	
    			$this->redirect(array('action' => 'admin_index'));
		  }else{
				$this->Session->setFlash("No se ha podido crear el Modelo");
				$this->log(__("No se ha podido crear el Modelo",true), LOG_DEBUG);
    			$this->redirect(array('action' => 'admin_index'));
		   }
		  
		} 
		
      }
      
      
     function __model_results($configName,$names){ 
       
      	$model = new Model("",$names,$configName);
      	
      	 if (is_object($model)) {
      	 	$primaryKey = $model->primaryKey;
			$useTable = $model->table;
			$useDbConfig = $configName;			
			$name = $model->name;
      	 }
      	 
      	 $fields = $this->__doFields($model,true);
      	 
		 foreach ($fields as $field => $value){		
		 	 	if ($field!="id")     
		          $array[]= array("name" => $field, "type" => $value["type"]);		
		 }
      	 
		 $this->set("fields",$array); 
		      	 
      	 $options = array(); 
		 if (class_exists('Validation')) {
			$parent = get_class_methods(get_parent_class('Validation'));
			$options = array_diff(get_class_methods('Validation'), $parent);
			foreach ($options as $option){
				$options_[$option]=$option;
			}
		 }
      	 
         $this->set("selector",$options_);        
      }
      
      
        
	function __getValidate($values) {
      	 $validateCount = count($values);
      	 $keys= array_keys($values);
      	 $validates="";
      	 $cont=0;
      	 if ($validateCount>0){
      	 	$validates .= "\tvar \$validate = array(\n";
      	 	
      	 	for($i=0; $i< $validateCount; $i++){
      	 		if (!empty($values[$keys[$i]])){
      	 			$val = "'" . $values[$keys[$i]] . "'";
      	 		  	$validates .= "\t\t'" . $keys[$i] . "' => array({$val})"; 
      	 			if ($i + 1 < $validateCount) {
						$validates .= ",";
					} 
					$validates .= "\n";  
					$cont++;
      	 		}      	 		 
      	 	}
      	 	$validates .= "\t);\n";      	 
      	 	$validates .= "\n";
      	  } 
      	  if ($cont == 0) {
      	  	return "";
      	  } else {
      	 	return $validates; 
      	  }
     }
      	
     function __getHasMany($arrayValues){     	
     	 $out="";
     	 $out .= "\tvar \$hasMany = array(\n";
     	 $cont = 0; 
     	 foreach ($arrayValues as $values){
	    	 if (!empty($values['alias']) && $values['alias']!="") {
	    	 	if($cont>0){
				 		$out .=",";
				}						
					$out .= "\t\t'{$values['alias']}' => array(\n";
					$out .= "\t\t\t'className' => '{$values['className']}',\n";
					$out .= "\t\t\t'foreignKey' => '{$values['foreignKey']}',\n";
					$out .= "\t\t\t'dependent' => false,\n"; 
					$out .= "\t\t)";
					$out .= "\n\n";
					$cont++;
				}
     	 }
     	 $out .= "\t);\n\n";
		return $out;
     }
     
     
     function __getHasOne($arrayValues) {  
     	   	$out="";
     	   	$out .= "\tvar \$hasOne = array(\n";
     	   	$cont = 0; 
     	   	foreach ($arrayValues as $values){
	    	  if (!empty($values['alias']) && $values['alias']!="") {	
	    	  if($cont>0){
				 	$out .=",";
				}
				$out .= "\t\t'{$values['alias']}' => array(\n";
				$out .= "\t\t\t'className' => '{$values['className']}',\n";
				$out .= "\t\t\t'foreignKey' => '{$values['foreignKey']}',\n";
				$out .= "\t\t\t'dependent' => false,\n"; 
				$out .= "\t\t)";  
				$out .= "\n\n";
				$cont++;
			   }
     	   	}
			$out .= "\t);\n\n";
			return $out;
     }
     
    
     function __getBelongsTo($arrayValues) { 
     		$out="";
     		$out .= "\tvar \$belongsTo = array(\n";	
     		$cont = 0; 
     		foreach ($arrayValues as $values){
     		 if (!empty($values['alias']) && $values['alias']!="") {
				if($cont>0){
				 	$out .=",";
				}
				$out .= "\t\t'{$values['alias']}' => array(\n";
				$out .= "\t\t\t'className' => '{$values['className']}',\n";
				$out .= "\t\t\t'foreignKey' => '{$values['foreignKey']}',\n";
				$out .= "\t\t\t'conditions' => '',\n";
				$out .= "\t\t\t'fields' => '',\n";
				$out .= "\t\t\t'order' => ''\n";
				$out .= "\t\t)";				 
				$out .= "\n\n";
				$cont++;
			  }
     		}
			$out .= "\t);\n\n";
			return $out;
     }
     
     function __getHasAndBelongsToMany($values){
     	// TODO hacer para muchas relaciones HasAndBelongsToMany y ampliar los campos
     	$out="";
     	if (!empty($values)) {
				$out .= "\tvar \$hasAndBelongsToMany = array(\n";
				$out .= "\t\t'{$values['alias']}' => array(\n";
				$out .= "\t\t\t'className' => '{$values['className']}',\n";
				$out .= "\t\t\t'joinTable' => '{$values['joinTable']}',\n";
				$out .= "\t\t\t'foreignKey' => '{$values['foreignKey']}',\n";
				$out .= "\t\t\t'associationForeignKey' => '{$values['associationForeignKey']}',\n";
				$out .= "\t\t\t'unique' => true,\n";
				$out .= "\t\t\t'conditions' => '',\n";
				$out .= "\t\t\t'fields' => '',\n";
				$out .= "\t\t\t'order' => '',\n";
				$out .= "\t\t\t'limit' => '',\n";
				$out .= "\t\t\t'offset' => '',\n";
				$out .= "\t\t\t'finderQuery' => '',\n";
				$out .= "\t\t\t'deleteQuery' => '',\n";
				$out .= "\t\t\t'insertQuery' => ''\n";
				$out .= "\t\t)";
				$out .= "\t);\n\n";
			}  
			  	
			return $out;
     }    
     
     /*create table name*/
     function __getTableName($name){     	 
     	$out="";
     	if (!empty($name)) {
				$out .= "\tvar \$useTable = '".$name."';";
		}	  	
		
		return $out;
     }    
	
	/* get list of tables bd*/
    function __getListTables() {
    	 
		$useDbConfig = $this->userDbConfig;
		$configs = get_class_vars('DATABASE_CONFIG');

		if (!is_array($configs)) {
			return $this->DbConfig->execute();
		}
		  
        $db =& ConnectionManager::getDataSource($useDbConfig); 
		$tables = $db->listSources();
		$arrayTables= Array();
		
		foreach ($tables as $table){
			$singular = $this->_modelName($table);
			$value =$this->_pluralName($table);
			$arrayTables[$value]=$singular;
		} 
		
		if (empty($arrayTables)) {			 
			$this->Session->setFlash(__('Your database does not have any tables'));	
			$this->log(__('Your database does not have any tables',true), LOG_DEBUG);		
		 	//$this->redirect(array('action' => 'admin_index'));	
		 	return false;		 
		}
				
		$count = count($arrayTables);
		if ($count > 0){ 
			 //$this->set('selectTables', $arrayTables);
			 return $arrayTables; 			
		} 
		return false; 
	}
	

	
	
	function __getListFieldsModel($configName,$names){ 
       
      	$model = new Model("",$names,$configName);
      	
      	 if (is_object($model)) {
      	 	$primaryKey = $model->primaryKey;
			$useTable = $model->table;
			$useDbConfig = $configName;			
			$name = $model->name;
      	 }
      	 $array= Array();
      	 $fields = $this->__doFields($model,true);
      	 
		 foreach ($fields as $field => $value){		
		 	 	if ($field!="id")     
		          $array[$field]= $field;		
		 }
      	 
		 if (count($array) > 0){
				return $array; 
		}
		return false;  
     }
	
	
	/*return ajax of rows of a bd table*/
	function admin_getListRows($names=null){
		//$this->autoRender = false; 
	
		Configure::write('debug', 0);
		$rows=Array();
				
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	  
 	    $rows=$this->__model_results2($this->userDbConfig,$names); 		
 	     
	    $this->set('rows', $rows); 
	    
	}
	
	
	
     function __model_results2($configName,$names){ 
     
      	$model = new Model("",$names,$configName);
      	if (!is_object($model)) {
			return false;
		}
		$fields = $model->schema();
      	
		foreach ($fields as $field => $value){	
		          $array[$field]= $field;		
		}
		
      	return $array;        
      }
	
	
}
?>